const App = getApp();
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName:''
    },
    hasUserInfo: false,
    canIUseGetUserProfile: false,
  },

  inputEvent(e) {
    let app = this
    let userInfo = app.data.userInfo
    userInfo.nickName = e.detail.value.trim()
    app.setData({
      userInfo
    })
  },

  onChooseAvatar(e) {
    let app = this
    let userInfo = app.data.userInfo
    wx.uploadFile({
      url: App.api_root + 'uploads/image',
      filePath: e.detail.avatarUrl,
      name: 'iFile',
      formData: {
        wxapp_id: App.getWxappId(),
      },
      success: function(res) {
        let result = typeof res.data === "object" ? res.data : JSON.parse(res.data);
        if (result.code === 1) {
          userInfo.avatarUrl = result.data.file_path
          app.setData({
            userInfo
          })
        }
      },
      complete: function() {
          // 所有文件上传完成
          console.log('upload complete');
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let app = this
    wx.login({
      success(res) {
        // 发送用户信息
        App._post_form('user/checkRegister', {
          code: res.code
        }, result => {
          if(result.data.userInfo) {
            let userInfo = app.data.userInfo
            userInfo.avatarUrl = result.data.userInfo.avatarUrl
            userInfo.nickName = result.data.userInfo.nickName
            app.setData({
              userInfo
            })
          }
        }, false, () => {
          wx.hideLoading();
        });
      }
    });
  },

  login() {
        let app = this;
        if(app.data.userInfo.nickName == '') {
          App.showError('请输入昵称');
          return false
        }
        if(app.data.userInfo.avatarUrl == 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0') {
          App.showError('请上传头像');
          return false
        }
        App.getUserInfo(app.data.userInfo, () => {
          // 跳转回原页面
          app.onNavigateBack();
        });
  },

  /**
   * 授权登录
   */
  getUserInfo(e) {
    let _this = this;
    App.getUserInfo(e, () => {
      // 跳转回原页面
      _this.onNavigateBack();
    });
  },

  /**
   * 暂不登录
   */
  onNotLogin() {
    let _this = this;
    // 跳转回原页面
    _this.onNavigateBack();
  },

  /**
   * 授权成功 跳转回原页面
   */
  onNavigateBack() {
    wx.navigateBack();
  },

})